import { createApp, h, render } from 'vue'
import Message from './message.vue'

const div = document.createElement('div')
div.classList.add('message-container')
document.body.appendChild(div)

const messageApp = createApp({
  data() {
    return {
      messages: [],
    }
  },
  render() {
    return h(
      'div',
      {},
      this.messages.map((msg) => h(Message, { ...msg }))
    )
  },
  methods: {
    addMessage(options) {
      this.messages.push(options)
      setTimeout(() => {
        this.removeMessage(options)
      }, options.duration || 6000)
    },
    removeMessage(target) {
      const index = this.messages.findIndex((message) => message === target)
      this.messages.splice(index, 1)
    },
  },
})

const app = messageApp.mount(div)

const message = (options) => {
  app.addMessage(options)
}
export default message

